package no.hib.bridge.net;

import no.hib.bridge.gui.SparMainGUI;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

public class BridgeHttpServer {
	int portNumber;
	String indexLocation = System.getProperty("user.home");
	Server server;
	SparMainGUI owner;

	/*
	 * default server port is 80
	 */
	public BridgeHttpServer(SparMainGUI owner) {
		this(owner, 80);
	}

	public BridgeHttpServer(SparMainGUI owner, int portNumber) {
		this.portNumber = portNumber;
		this.owner = owner;

		SelectChannelConnector connector1 = new SelectChannelConnector();
		connector1.setPort(portNumber);
		connector1.setThreadPool(new QueuedThreadPool(20));
		server = new Server();
		server.setConnectors(new Connector[] { connector1 });
		Handler h = new BridgeHttpHandler(owner);

		ResourceHandler resource_handler = new ResourceHandler();

		resource_handler.setResourceBase("./web-content");

		resource_handler.setDirectoriesListed(true);
		resource_handler.setWelcomeFiles(new String[] { "index.html" });

		HandlerList handlers = new HandlerList();
		handlers.setHandlers(new Handler[] { resource_handler, h });
		server.setHandler(handlers);
	}

	public void start() throws Exception {
		owner.addMessage("Server Startup...");
		server.start();
	}

	public void stop() throws Exception {
		owner.addMessage("Stopping Server...");
		server.stop();
		server.join();
	}

	public void setHandler(ContextHandlerCollection context) {
		server.setHandler(context);
	}

	public boolean isStarted() {
		return server.isStarted();
	}

	public boolean isStopped() {
		return server.isStopped();
	}

}
